package com.example.happiness.controller.admin;

import com.example.happiness.pojo.Serve;
import com.example.happiness.pojo.adminvo.AdminServeVO;
import com.example.happiness.result.Result;
import com.example.happiness.service.admin.AdminServeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@Api(tags = "服务项相关接口")
@Slf4j
@RestController
@RequestMapping("/admin/serve")
public class AdminServeController {

    @Autowired
    AdminServeService serveService;
    @Autowired
    RedisTemplate redisTemplate;

    @GetMapping("/selectServe")
    @ApiOperation("查询服务项列表")
    public Result<List<AdminServeVO>> selectServe() {
        List<AdminServeVO> serveList = serveService.selectServe();
        return Result.success(serveList);
    }

    @PostMapping("/addServe")
    @ApiOperation("添加服务项")
    public Result addServe(@RequestBody Serve serve){
        serveService.addServe(serve);
        CloseCache("serve_*");
        return Result.success();
    }

    @DeleteMapping("/deleteServe")
    @ApiOperation("删除服务项")
    public Result deleteServe(Integer sid){
        CloseCache("serve_*");
        return serveService.deleteServe(sid);
    }

    @PutMapping("/updateServe")
    @ApiOperation("修改服务项")
    public Result updateServe(@RequestBody Serve serve){
        CloseCache("serve_*");
        serveService.updateServe(serve);
        return Result.success();
    }

    private void CloseCache(String pattern){
        Set<String> keys = redisTemplate.keys(pattern);
        System.out.println(keys);
        if (keys != null && !keys.isEmpty()) {
            redisTemplate.delete(keys);
        }
    }
}
